package leetcode.datastructure.str;

import java.util.ArrayList;
import java.util.List;

public class Program6StringZConvert {
    public Program6StringZConvert() {
    }
    public String convert(String s, int numRows) {
        return person(s, numRows);
//        return office(s, numRows);
    }

    public String office(String s, int numRows) {
        if(numRows < 2) return s;
        List<StringBuilder> rows = new ArrayList<StringBuilder>();
        for(int i = 0; i < numRows; i++) rows.add(new StringBuilder());
        int i = 0, flag = -1;
        for(char c : s.toCharArray()) {
            rows.get(i).append(c);
            // flag = - flag： 在达到 Z 字形转折点时，行执行反向。
            if(i == 0 || i == numRows -1) flag = - flag;
            i += flag;
        }
        StringBuilder res = new StringBuilder();
        for(StringBuilder row : rows) res.append(row);
        return res.toString();
    }

    public String person(String s, int numRows) {
        if (s.length() <= numRows || numRows == 1) {
            return s;
        }
        // 展示样式是n
        int length = s.length();

        List<StringBuilder> rowSb = new ArrayList<>();
        for(int i = 0; i < numRows; i++) rowSb.add(new StringBuilder());

        for (int i = 0; i < numRows; i++) {
            int j = i;
            boolean flag = true;
            while (j < length) {
                rowSb.get(i).append(s.charAt(j));


                // 递推 i 没有准确覆盖
                if (i == numRows - 1 || i == 0) {
                    j += 2 * (numRows - 1);
                } else {
                    if (flag) {
                        j += 2 * (numRows - i - 1);
                    } else {
                        j += 2 * i;
                    }

                }
                flag = !flag;
            }
        }
        StringBuilder res = new StringBuilder();
        for(StringBuilder row : rowSb) res.append(row);
        return res.toString();
    }

    public static void main(String[] args) {
        Program6StringZConvert obj = new Program6StringZConvert();

        System.out.println(obj.convert("PAYPALISHIRING", 4));
    }
}
